package com.yunhe.common.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.yunhe.common.metadata.BaseExcelModel;
import com.yunhe.common.util.CollectionUtil;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: DongWenYu
 * @Date: 2021/4/28 10:36
 */
public class UploadDataListener extends AnalysisEventListener<BaseExcelModel> {

    private static final Logger logger = LoggerFactory.getLogger(UploadDataListener.class);

    /**
     * 实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 50;
    List<BaseExcelModel> list = new ArrayList<>();

    private String fileName  = "未命名";

    private Object obj = null; // object为接口

    private String methodName = "upload"; //方法名，默认为upload

    private Long entryPerson = null ; //录入人


    private Long orgId = null; //组织id

    private Long stationId = null;

    private String dataType = null; // 数据类型

    public UploadDataListener(Object obj , String methodName , String fileName){
        this.obj = obj;
        this.methodName = methodName;
        this.fileName = fileName;
    }

    public UploadDataListener(Object obj , String fileName){
        this.obj = obj;
        this.fileName = fileName;
    }


    public UploadDataListener(Object obj,String fileName , Long entryPerson, Long orgId, String dataType) {
        this.obj = obj;
        this.fileName = fileName;
        this.entryPerson = entryPerson;
        this.orgId = orgId;
        this.dataType = dataType;
    }

    public UploadDataListener(Object obj,String fileName , Long entryPerson) {
        this.obj = obj;
        this.fileName = fileName;
        this.entryPerson = entryPerson;
    }

    public UploadDataListener(Object obj ,String fileName,Long entryPerson , Long stationId) {
        this.obj = obj;
        this.stationId = stationId;
        this.entryPerson = entryPerson;
        this.fileName = fileName;
    }

    @Override
    public void invoke(BaseExcelModel data, AnalysisContext context) {
        logger.debug("解析到一条数据:{}", JSON.toJSONString(data));
        if (!data.isEmpty()) {
            for (BaseExcelModel baseExcelModel : list){
                //同批次导入存在相同数据，子类需重写equals
                if (data.equals(baseExcelModel)){
                    baseExcelModel.update(data);
                    data = null;
                    break;
                }
            }
            if ( data != null){
                data.check();
                list.add(data);
            }
        }
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            try {
                saveData();
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
            // 存储完成清理 list
            list.clear();
        }
    }

    @SneakyThrows
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        list.clear();
        logger.info("fileName:"+fileName+"所有数据解析完成");

    }

    private void saveData() throws InvocationTargetException, IllegalAccessException {
        Class<?> clazz = obj.getClass();
            Method[] methods = clazz.getMethods();
            if(methods.length>1){
                List<Method> methodList = Arrays.stream(methods).filter(method -> {
                    return methodName.equals(method.getName());
                }).collect(Collectors.toList());
                if(!CollectionUtil.isEmpty(methodList)){
                    Method method = methodList.get(0);
                    logger.info("文件名:{},{}条数据，开始存储数据库！", fileName,list.size());
                    if (method.getParameterCount() == 2){
                        method.invoke(obj, list , entryPerson);
                    }else if (method.getParameterCount() == 1){
                        method.invoke(obj, list);
                    }else if (method.getParameterCount() == 4){
                        method.invoke(obj, list,entryPerson,orgId,dataType);
                    }else if (method.getParameterCount() == 3){
                        method.invoke(obj,list,entryPerson,stationId);
                    }
                }
            }


    }
}

